<?
    require_once("config.php");
    require_once("objects/editable_form_elements.php");
    require_once("objects/form_elements.php");
    
    $menu = new Menu("Search");
    $menu->AddItem(new MenuItem("Search Listings","search.php"));
    MenuManager::AddMenu("Search Listings",$menu);
    MenuManager::AddMenu("Search Results",$menu);
    
    if ($_GET['action'] == 'ajax') {
        $type = DBM::FetchOne("SELECT type FROM listing_structure WHERE id=$_POST[structid];");
        $type = "Editable" . strtoupper($type{0}) . substr($type,1);
        $searchable = new $type($_POST['structid'],2);
        
        echo $_POST['lineid'] . "|" . $searchable->__toString();
    }
    else if ($_POST) {
        $conditions = array();
        $matchings = array();
        
        for ($x = 0; $x < $_POST['count']; $x++) {
            $structinfo = DBM::FetchRow("SELECT * FROM listing_structure WHERE `id`='" . $_POST["fieldtitle_$x"] . "';");
            
            $matches = array();
            // look thru the options, find which ones are checked  
            $ops = explode(",",$structinfo['options']);
            for ($y = 0; $y < count($ops); $y++) {
                if ($_POST["formitem_$structinfo[id]_checkbox_$y"]) {
                    $optname = $ops[$y];
                    $matches[$optname] = 1;
                }
                else if ($_POST["formitem_$structinfo[id]"]) {
                    $matches = $_POST["formitem_$structinfo[id]"];
                }
            }
            
            $conditions[$structinfo['id']] = $matches;
            $matchings[$structinfo['id']] = $_POST["matchtype_$x"];
        }
        
        $listingmatches = array();
        
        foreach ($conditions as $structid => $conds) {
            $querybase = "SELECT listingid FROM listing_data WHERE structureid='$structid' AND (";
            
            $count = 0;
            if (is_array($conds)) {
                $max = count($conds);
                foreach ($conds as $condition=>$val) {
                    $querybase .= "(data LIKE '%" . SettingManager::EncodeSettingName($condition) . ":$val%' OR data LIKE '%$condition%')";
                    
                    if ($count != $max - 1) {
                        if ($matchings[$structid] == "matchany") $querybase .= " OR ";
                        else $querybase .= " AND ";
                    }   
                    
                    $count++;
                }
            }
            else {
                if ($matchings[$structid] == "matchany")
                    $querybase .= "data LIKE '%$conds%'";
                else
                    $querybase .= "data LIKE '$conds'";
            }
        }
            
            $querybase .= ");";

	    if ($count == 0) {
            $listingmatches = array();
	    }
	    else {
            $results = DBM::FetchAllRows($querybase);
            foreach ($results as $row) {
                if ($listingmatches[$row['listingid']]) $listingmatches[$row['listingid']]++;
                else $listingmatches[$row['listingid']] = 1;
            }
        }
        
        foreach ($listingmatches as $match => $count) {
            $listingmatches[$match] = floor(100 * ($count / count($conditions)));
        }
        
        Functions::PrintHeader("Search Results");
        
        if (count($listingmatches) == 0) {
            InfoMessage::Show("No Results Found","No listings with the criteria you specified could be found.  Try searching with less specific requests and try again.");
        }
        else {
            foreach ($listingmatches as $listing => $matchamount) {
                // make sure it's valid:
                $query = "SELECT * FROM listings WHERE id=$listing";
                $res = DBM::CountRows($query);
                if ($res > 0)
                    echo new ListingRow($listing);
                else continue;
            }
        }
        
        Functions::PrintFooter();
    }
    else {
        Functions::PrintHeader("Search Listings");
        ?>
        
        <script type='text/javascript'>
            var count = 0;
            function addCondition() {
                base = $("itemtemplate");
                base = base.cloneNode(true);
                base.id = "lineitem_" + count;
                
                // take advantage of xeditableform
                form = new EditableForm();
                refs = form._update_ids(base,count);
                
                refs.removebutton.setAttribute("onClick","removeCondition(" + count + ")");
                $("conditions").appendChild(base);
                updateSearchable(refs.fieldtitle);
                
                count++;
                $("count").value = count;
            }
            
            function updateSearchable(element) {
                id = element.id.split("_");
                lineid = id[1];
                structid = element.value;
                
                $("title_type_holder_" + lineid).innerHTML = "Please Wait...";
                new Ajax.Request("search.php?action=ajax",{
                    method : "post",
                    parameters : {"lineid" : lineid, "structid" : structid},
                    onSuccess : function (transport) {
                        obj = transport.responseText.split("|");
                        $("title_type_holder_" + obj[0]).innerHTML = obj[1];
                    }
                });
            }

            function removeCondition(id) {
                $("conditions").removeChild($("lineitem_" + id));
            }
            
            function toggleShow(id) {
                if ($(id).style.display == "none") {
                    $(id).style.display = "block";
                    $(id + "_toggler").innerHTML = "Hide search help";
                }
                else {
                    $(id).style.display = "none";
                    $(id + "_toggler").innerHTML = "Need help with searching?";
                }
            }
        </script>
        
        <div style='display:none;'>
            <table class='searchtable' id='itemtemplate'>
                <tr>
                    <td style='border-right:dotted 1px gray'>
                        <input type='button' class='remove' name='removebutton' style='margin-right:35px;' value="Remove" />
                    </td>
                    <td><span style='font-size:14pt;'>Where</span></td>
                    <td> 
                        <?
                            $struct = DBM::FetchAllRows("SELECT * FROM listing_structure WHERE type <> 'header' ORDER BY location ASC;");
                            $stuff = array();
                            foreach ($struct as $row) {
                                $stuff[$row['id']] = $row['title'];
                            }
                            
                            $dropdown = new DropdownMenu("fieldtitle");
                            $dropdown->attributes->onChange = "updateSearchable(this)";
                            
                            $stuff['rent'] = 'Rent';
                            foreach ($stuff as $val => $title) { $dropdown->AddOption($val,$title); }
                            echo $dropdown;
                        ?>
                    </td>
                    <td>
                        <select name='matchtype'>
                            <option value='matchany'>matches any of</option>
                            <option value='matchall'>matches all of</option>
                        </select>
                    </td>
                    <td style='width:100%'>
                        <div name='title_type_holder' class='title_type'>
                            <span style='color:gray;'>Please wait...</span>
                        </div>
                    </td>
                </tr>
            </table>
        </div>
        <h2>Lookup Listing (by ID)</h2>
        <form method="GET" action="listing.php">
	<input type='hidden' name='action' value='view' />
       <table class='cgltable' align='center'>
        <thead>
                <tr>
                    <th colspan='2'>Lookup a Listing</th>
                </tr>
           </thead>
                <tr>
                    <td class='required label'>Listing ID</td>
                    <td><input type='text' name='id' size="4" /></td>
                </tr>
                <tfoot>
                <tr>
                    <td colspan='2'><input type='submit' value='Lookup' /></td>
                </tr>
                </tfoot>
            </table>
        </form>
        <br />
        <br />
        <h2>Search for Listing</h2>
        <a id='searchHelp_toggler' href='javascript:toggleShow("searchHelp");'>Need help with searching?</a>
        <br />
        <div id='searchHelp' style='display:none;'>
            <?php
                InfoMessage::Show("Help with searching",
                    "This form allows you to narrow down your search and look for the exact listing that you want.  " .
                    "To search, select from the first dropdown menu the field that you want to search.  Then select " .
                    "whether you want to search for exact matches or partial matches.  Finally, either check the boxes " . 
                    "or type in the terms that you want to search for.<br /><br />For example, if you wanted to find all " .
                    "apartments with 3 bedrooms that allowed pets, you would select 'Number of Bedrooms' from the first " .
                    "dropdown, then check the box that says '3'.  To make the search narrower to allow pets, click 'Add Condition' " .
                    "and repeat for 'Allows Pets'.".
                    
                    "<br /><br />" .
                    "If you wanted to find all listings that were either fully or semi-furnished and had electric and water, you would select " .
                    "'Furnishings' from the first dropdown menu, then check the boxes for 'Semi-Furnished' and 'Fully-Furnished'. " .
                    "Then, (after clicking +Add Condition) select 'Utilities' from the next dropdown.  For this line, select 'matches all of' " .
                    "from the dropdown that currently says 'matches any of'.  Then select the desired utilities, in this case electric and " .
                    "water."
                );
            ?>
            <hr />
        </div>
        <div style='border-bottom:solid 2px black;'>&nbsp;</div>
        <form method="POST" action='search.php'>
        <input type='hidden' name='count' id='count' value='0' />
        <div id='conditions'>
            
        </div>
        <input type='button' class='add' value='Add Condition' onClick='addCondition()' />
        <hr />
        <input type='submit' value='Search' />
        </form>
        <script type='text/javascript'>addCondition();</script><br /><br />
        <i>Note: </i> Results are sorted in order of best match.<br />
        <?
        Functions::PrintFooter();
    }
?>
